"------------------------------------------------------------------------------
" Wrap text with specific tokens. The 'Surround' functions currently supports
" two strategies for surrounding text: 'eol', surround text from cursor to the
" end of line; and 'word', surround only the word 
"------------------------------------------------------------------------------

fu! Surround(args)	
	let [action, open, close] = a:args
	let l:ccol = getcurpos()[2]
	let l:line = getline('.')
	
	if line[ccol] == ''
		call setline('.' , line . open . close)
		call cursor('.', len(getline('.')))
		return
	endif
	
	let l:cursor_to_end = line[ccol:]
	let l:line_to_cursor = line[:ccol]
	
	if action == 'eol'
		call setline('.', line_to_cursor . open . cursor_to_end . close)
		call cursor('.', len(getline('.')))
	elseif action == 'word'
		let l:word = expand("<cword>")
		let l:cursor_to_end = substitute(cursor_to_end, word, open . word . close, '')
		call setline('.', line_to_cursor . cursor_to_end)
		call cursor('.', len(word) + ccol + 2)
	endif
endf

command! -nargs=+ Surround
	\ let s:args = split(<q-args>) |
	\ let s:key = s:args[0] |
	\ let s:str = printf('nnoremap %s <esc>:call Surround(%s)<cr>', s:key, s:args[1:]) |
	\ exe s:str

"Surround <leader>( eol ( )
"Surround <leader>{ word { }
